package messages;

import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import security.Hash;
import security.crypto.AssimEncryption;
import security.crypto.SimmEncryption;
import utils.Base64Processing;
import utils.XmlSerializationUtils;

public class UserPassSKExchangeMessage implements Convertible {

	private static final long serialVersionUID = 1L;

	private String _cipheredSessionKey;

	public UserPassSKExchangeMessage(){		
	}

	public UserPassSKExchangeMessage(String passHash, PublicKey clientPubKey, Key sessionKey){

		Key passwordKey = SimmEncryption.generateKeyFromPassHash(passHash);
		
		String sessionKeyString = Base64Processing.encodeData(sessionKey.getEncoded());

		String pkCipheredSessionKeyString = AssimEncryption.cipher(sessionKeyString, clientPubKey);

		_cipheredSessionKey = SimmEncryption.cipherString(pkCipheredSessionKeyString, passwordKey);
	}

	public SecretKey getSessionKey(String password, PrivateKey privateKey) {
		Key passwordKey = SimmEncryption.generateKeyFromPassHash(Hash.getStringHash(password));
		String pkCipheredString = SimmEncryption.decipherString(_cipheredSessionKey, passwordKey);

		String sessionKeyString = AssimEncryption.decipher(pkCipheredString, privateKey);
		byte[] sessionKeyBytes = Base64Processing.decodeData(sessionKeyString);

		return new SecretKeySpec(sessionKeyBytes, "AES");
	}

	@Override
	public Element convertToCanonic(Document doc) {
		Element el = doc.createElement("UserPassSKExchangeMessage");

		if (_cipheredSessionKey != null) {
			Element childEl = doc.createElement("CipheredSessionKey");
			childEl.setTextContent(_cipheredSessionKey);
			el.appendChild(childEl);

		} 

		return el;
	}

	@Override
	public Object convertFromCanonic(Element el) {
		this._cipheredSessionKey = XmlSerializationUtils.getTextValue(el, "CipheredSessionKey");
		return this;
	}



}
